from configparser import ConfigParser
from context.curry import Curry
from common.constants import Constants

class ContextObject(object):
    """
    just parse config file and initiates context instances
    """
    def __init__(self, config_file):
        self.config_file = config_file        
        self.cp = ConfigParser()
        self.cp.read(self.config_file)
        self.sections = self.cp.sections()
        self.insts_list = []        
        
    def collect_instances(self):
        for section in self.sections:
            new_instance = type(section,(),{})()
            options = self.cp.options(section)
            self.insts_list.append(new_instance)
            new_instance.__setattr__('__name__',section)
            for option in options:
                new_instance.__setattr__(option,self.cp.get(section,option))                                
            new_instance.__setattr__('get_matching_properties', Curry(self.get_matching_properties, new_instance))
                
    def get_matching_properties(self, instance, string):
        return [instance.__dict__[property] for property in instance.__dict__ if not callable(instance.__dict__[property]) and string in property]

    def store(self, obj, option, value):        
        section = obj.__name__
        self.cp.set(section, option, value)
        self.cp.write(open(self.config_file, 'w'))
                
    def make_context(self):
        insts_dict = {}
        for inst in self.insts_list:
            insts_dict[inst.__name__] = inst            
        insts_dict['__dict__'] = insts_dict
        insts_dict['store'] = self.store
        return type('context',(),insts_dict)()
    
class Context(object):
    """
    Initiates context objects with config values
    """
    config = Constants.CONFIG_FILE
    def __init__(self):        
        ct = ContextObject(self.config)
        ct.collect_instances()
        self.context = ct.make_context()

    def find_context_item(self,context_instance,item_name):
        if item_name in context_instance.__dict__:
            return context_instance.__dict__[item_name]    

    def find_all_context_items(self):
        return self.context.__dict__.pop('__dict__')
    
    def get_matching_instance(self, string):
        strings = []
        instances = self.find_all_context_items()
        for instance_name in instances:
            instance = instances[instance_name]
            if string in instance.__name__:
                strings.append(instance.__name__)
        return strings
